package com.example.zhxy.controller;

import com.example.zhxy.pojo.Admin;
import com.example.zhxy.pojo.LoginForm;
import com.example.zhxy.pojo.Student;
import com.example.zhxy.pojo.Teacher;
import com.example.zhxy.service.AdminService;
import com.example.zhxy.service.StudentService;
import com.example.zhxy.service.TeacherService;
import com.example.zhxy.util.CreateVerifiCodeImage;
import com.example.zhxy.util.JwtHelper;
import com.example.zhxy.util.Result;
import com.example.zhxy.util.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * CJ
 */
@Api(tags = "其余功能控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @ApiOperation("验证码功能")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();

        //获取图片上的验证码
        String verifiCode =new String( CreateVerifiCodeImage.getVerifiCode());
        System.out.println(verifiCode);
        //将验证码放入session
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        //放回验证码
        System.out.println(session.getAttribute("verifiCode"));
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation("登录功能")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm , HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println(session.getAttribute("verifiCode"));
        if("".equals(session.getAttribute("verifiCode"))||null==session.getAttribute("verifiCode")){
            return Result.fail().message("验证码失效");
        }
        System.out.println(loginForm);
        if(!session.getAttribute("verifiCode").equals(loginForm.getVerifiCode())){
            return Result.fail().message("验证码错误");
        }
        request.removeAttribute("verifiCode");
        Map<String,Object> map=new LinkedHashMap<>();
        switch(loginForm.getUserType()){
            case 1:
                Admin admin=adminService.login(loginForm);
                try{
                    if(admin!=null){

                        map.put("token",JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);
                }catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }


            case 2:
                Student student=studentService.login(loginForm);
                try{
                    if(student!=null){

                        map.put("token",JwtHelper.createToken(student.getId().longValue(),2));
                    }else {
                        throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);
                }catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 3:
                Teacher teacher =teacherService.login(loginForm);
                try{
                    if(teacher!=null){

                        map.put("token",JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else {
                        throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);
                }catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }


        }
        return Result.fail().message("查无此用户");

    }
    @ApiOperation("根据信息跳转功能+token口令")
    @GetMapping("/getInfo")
    public Result getInfo(@RequestHeader("token") String token){
        boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        Long userId=JwtHelper.getUserId(token);
        Integer userType=JwtHelper.getUserType(token);
        Map<String ,Object> map=new LinkedHashMap<>();
        map.put("userType",userType);
        switch (userType){
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getById(userId);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getById(userId);
                map.put("user",teacher);
                break;
        }
        return Result.ok(map);
    }
    @ApiOperation("图片文件统一上传")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(@RequestPart("multipartFile")MultipartFile multipartFile){
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName=uuid+originalFilename.substring(i);
        String portraitPath="D:/SSM/zhxy/target/classes/public/upload/"+newFileName;
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path="upload/"+newFileName;

        return Result.ok(path);
    }
    @ApiOperation("更新密码")
    @PostMapping("/updatePwd/{password}/{newPassWord}")
    public Result updatePwd(@PathVariable String password,@PathVariable String newPassWord,@RequestHeader("token") String token){
        Integer userId = JwtHelper.getUserId(token).intValue();
        boolean b=adminService.updatePwd(password,newPassWord,userId);
        if(b){
            return Result.ok().message("修改成功");
        }else return Result.fail().message("原密码错误修改失败");
    }



}
